package com.n.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.n.application.SystemCache;
import com.n.common.BaseAction;
import com.n.dao.CodeValueDao;
import com.n.model.CodeValue;
import com.n.util.Constant;

@Controller
@RequestMapping("/dic")
public class CodeValueAction extends BaseAction {
	
	static final String PRE_PATH = "/admin/dic/";
	
	@Autowired
	CodeValueDao codeValueDao;
	
	
	@RequestMapping(value="save.do")
	@ResponseBody
	public String save(HttpServletRequest request){
		String sid = request.getParameter("id");
		CodeValue c = new CodeValue();
		c.setType(Integer.parseInt(request.getParameter("type")));
		c.setCode(request.getParameter("code"));;
		c.setValue(request.getParameter("value"));
		if(!StringUtils.isEmpty(sid)){
			c.setId(Integer.parseInt(sid));
		}
		codeValueDao.merge(c);
		
		rebuildCache();
		
		return SUCCESS;
	}
	
	@RequestMapping(value="list.do")
	public String list(HttpServletRequest request, ModelMap model){
		
		List<CodeValue> customer_area_data = (List<CodeValue>)codeValueDao.loadByType(Constant.CVTYPE_CUSTOMER_AREA);
		model.put("customer_area_data", customer_area_data);
		
		List<CodeValue> supplier_area_data = (List<CodeValue>)codeValueDao.loadByType(Constant.CVTYPE_SUPPLIER_TYPE);
		model.put("supplier_type_data", supplier_area_data);
		
		List<CodeValue> pay_type_data = (List<CodeValue>)codeValueDao.loadByType(Constant.CVTYPE_PAY_TYPE);
		model.put("pay_type_data", pay_type_data);
		
		return PRE_PATH + "index";
	}
	
	@RequestMapping(value="load.do")
	@ResponseBody
	public String load(HttpServletRequest request){
		String sid = request.getParameter("id");
		if(StringUtils.isEmpty(sid)){
			return ERROR;
		}
		int id = Integer.parseInt(sid);
		CodeValue c = codeValueDao.load(CodeValue.class, id);
		JSONObject json = JSONObject.fromObject(c);
		json.put("success", SUCCESS);
		
		rebuildCache();
		
		return json.toString();
	}
	
	@RequestMapping(value="del.do")
	@ResponseBody
	public String del(HttpServletRequest request){
		String sid = request.getParameter("id");
		if(StringUtils.isEmpty(sid)){
			return ERROR;
		}
		int id = Integer.parseInt(sid);
		codeValueDao.del(id);
		
		rebuildCache();
		
		return SUCCESS;
	}
	
	private void rebuildCache(){
		SystemCache.buildCodeValue(codeValueDao);
	}

}
